import os
import pygame as pg

if not pg.font:
    print("Warning, fonts disabled")

main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, "data")


def load_image(name, colorkey=None, scale=1):
    fullname = os.path.join(data_dir, name)
    image = pg.image.load(fullname)
    size = image.get_size()
    size = (size[0] * scale, size[1] * scale)

    image = image.convert_alpha()
    image = pg.transform.scale(image, size)
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey, pg.RLEACCEL)
    return image, image.get_rect()
#def refresh(cacti=False, (player, player.rect), player_pos_y, background_surface):
# updates screen so i don't have to keep calling blit() and flip()
#    screen.blit(background_surface, (0, 0))
#    screen.blit(player, (0, player_pos_y))
#    if cacti:
#        screen.blit(cactus.image[0], (cactus_pos, player_pos_y - 10))

def player_jump(background, height, player_surface, player, screen):
    # modifies rect value, blits to screen
    """Moves player character upwards"""
    player.y -= height
    screen.blit(background, (0, 0))
    screen.blit(player_surface, (0, player.y))
    

def load_sound(name):
    class NoneSound:
        def play(self):
            pass

    if not pg.mixer or not pg.mixer.get_init():
        return NoneSound()
    fullname = os.path.join(data_dir, name)
    try:
        sound = pg.mixer.Sound(fullname)
    except pg.error:
        print("Cannot load sound: %s" % fullname)
        raise SystemExit(str(geterror()))
    return sound

class Cactus(pg.sprite.Sprite):
    """main obstacles"""
    def __init__(self):
        pg.sprite.Sprite.__init__(self)

        original_image = load_image("cactus.png")
        self.image = (pg.transform.scale(original_image[0], (50, 88)), original_image[1])
        self.rect = self.image[1]

class Dino(pg.sprite.Sprite):
    """creates a running dino"""
    def __init__(self, image):
        pg.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect(midleft=SCREENRECT.midleft)

def main():
    pg.init()

    # game constants
    SCREENRECT = pg.Rect(0, 0, 640, 480)
    cactus_pos = 600
    dino_pos_y = 314
    dino_coords = (0, 314)
    cactus_coords = (600, 304)
    ground_pos = 314
    score = 0

    # set display up
    screen = pg.display.set_mode(SCREENRECT.size, pg.SCALED)
    pg.display.set_caption("Dino Game!")
    background = pg.Surface(screen.get_size())
    background = background.convert()
    background.fill((255, 255, 255))


    # putting text on the background
    if pg.font:
        start_msg = "Press space to begin!"
        msg = "Score: %d" % score
        font = pg.font.Font(None, 36)
        start_text = font.render(start_msg, 1, (10, 10, 10))
        text = font.render(msg, 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width() / 2)
        start_text_pos = start_text.get_rect(centerx=background.get_width() / 4)
        # background.blit(text, textpos)
    screen.blit(background, (0, 0))
    screen.blit(start_text, start_text_pos)


    # load images
    clock = pg.time.Clock()
    dino = load_image("transparent.png", scale=1)
    cactus = Cactus()

    # set player and enemy positions
    dino[1].move_ip(0, 314)
    cactus.rect.move_ip(600, 314)

    # cactus = load_image("cactus.png")
    # cactus[0] = pg.transform.scale(cactus[0], (50, 88))

    # load sounds
    press_sound = load_sound("button-press.mp3")
    score_sound = load_sound("score-reached.mp3")
    hit_sound = load_sound("hit.mp3")

    # initialize groups
    # cacti = pg.sprite.Group()

    # TODO: write a function to set the base y-position based on the screen size
    screen.blit(dino[0], (0, dino_pos_y))
    pg.display.flip()
    
    # start screen
    while True:
        event = pg.event.poll()
        if event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
#             dino_pos_y -= 100
#             screen.blit(background, (0, 0))
#             screen.blit(dino[0], (0, dino_pos_y))
            player_jump(background, 120, dino[0], dino[1], screen)
            press_sound.play()
            pg.display.update()
            pg.time.wait(100)
            break
        elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
            pg.quit()
            return

    going = True
    failed = False
    while going:
        clock.tick(30)
#        print("Dino pos x: %d, Dino pos y %d" % (dino[1].x, dino[1].y))
#        print("Cactus pos x: %d, Cactus pos y %d" % (cactus.rect.x, cactus.rect.y))
#        print("Ground pos: %d" % (ground_pos))
        # print(dino[1])
        for event in pg.event.get():
            if event.type == pg.QUIT:
                going = False
            elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
                going = False
            elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
                # dino "jumps"
                pg.time.wait(100)
                dino_pos_y -= 120
                # player_jump(background, 120, dino[0], dino[1], screen)
                press_sound.play()
            else:
                dino_pos_y = ground_pos
        # dino[1].move_ip(50, dino_pos_y)
        dino[1].top = dino_pos_y

        score += 1
#        print("Score: %d" % score)
        if score % 100 == 0:
            score_sound.play()

        if cactus.rect.colliderect(dino[1]):
            text = font.render("Failed! Press a key to continue or Esc to exit!", 0, (10, 10, 10))
            textpos = text.get_rect(centerx=background.get_width() / 2)
            screen.blit(background, (0, 0))
            screen.blit(text, textpos)
            pg.display.update()
            failed = True
            continue

        # changes positions 
        if cactus_pos < -20:
            cactus_pos = 600
        else:
            cactus_pos -= 5 
        cactus.rect.left = cactus_pos

        if failed is True:
            score = 0
            for event in pg.event.get():
                if event.type == pg.KEYDOWN:
                    break
            failed = False 
            # cactus.rect.move_ip(600, 314) 
            cactus_pos = 600 
            dino[1].x = 0
        # animates the jump:
        # blits background over screen
        # blits dino next to show movement
        # when the position is reset the dino comes down
        screen.blit(background, (0, 0))
        screen.blit(dino[0], (0, dino_pos_y))
        screen.blit(cactus.image[0], (cactus_pos, ground_pos - 10))
        # print(score)

        # the text is blitted to the screen next
        # since the background obscured the previous text, it shows up fine
        # do not blit anything to the background as it is used to clear the screen
        # objects blitted to the background will persist as the screen changes
        msg = "Score: %d" % score
        text = font.render(msg, 0, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width() / 2)
        screen.blit(text, textpos)
        pg.display.update()
        # pg.time.wait(100)
    # pg.time.wait(1000)
#    print("dino rect")
#    print(dino[1])
#    print("cactus rect")
#    print(cactus.rect)
    pg.quit()
if __name__ == "__main__":
    main()
